package com.woniuxy.shiro;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * * @: JWT过滤器，拦截token信息，自定义的过滤器
 * @Author：向天浩
 * @Date：2022/2/23 14:03
 * @Description :
 */

public class JwtFilter extends BasicHttpAuthenticationFilter {
    /**
     *功能描述 ;；这里一般是用于统一后端处理跨域，后端跨域的方案有多个，但是同一时间只能使用一种方案。前端也有方法处理跨域
     * @Author: 向天浩
     * @Date: 2022/2/23 14:06
     * @param request
     * @param response 
     * @return boolean
     * 这个处理跨域是固定写法，不需要记住，使用的时候复制就行
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


    /**
     *功能描述 ;:token认证入口，进行业务逻辑处理，和后续过滤器方法的调用
     * @Author: 向天浩
     * @Date: 2022/2/23 17:01
     * @param request
     * @param response
     * @param mappedValue
     * @return boolean
     */
    @Override
    //isAccessAllowed;允许访问
    //
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //检查认证请求，获取请求头中的token
        //isLoginAttempt；表示是登录请求
        if (isLoginAttempt(request,response)) {
            try {
                //执行登录subject.login方法
                executeLogin(request,response);
            } catch (Exception e) {
                //如果请求头中没有token，跳转到401controller返回前端的请求
                response401(request,response);
                e.printStackTrace();
            }
        } else{//如果请求头没有token则会被拦截进入错误页面
            response401(request,response);
            return false;
        }

        return true;
    }
    //创建我们调用401页面的方法
    private void response401(ServletRequest request, ServletResponse response) {
        //强制转换成httpservlet，他们是子父类关系,我们要做请求转发
        HttpServletResponse response1 = (HttpServletResponse) response;
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //登录请求判断，尝试获取请求头中的token信息
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {

        HttpServletRequest request1=(HttpServletRequest)request;
        //从请求头中获取token的信息;所以是使用request来获取，这个Authorization是和前端对应的参数名字
        String token = request1.getHeader("Authorization");

        return token!=null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest request1 = (HttpServletRequest) request;
        //从请求头中获取token的信息
        String token = request1.getHeader("Authorization");
        //因为引入了shiro框架，所以直接使用getsubject().login()。login中的参数是一个token，
        //在这里使用的是我们自定义的token，不是使用它自带的UsernamePasswordToken
        getSubject(request,response).login(new MyJwtToken(token));

        return true;
    }
}
